package com.runmyai.aitools.text;


import com.runmyai.aitools.utils.Constants;

/**
 * @author wry
 */
public class TextPostProcessor {

    /**
     * 粗体字+冒号 **标题**: 仅用于后处理
     */
    public static final String BOLD_REGEX = "\\*\\*.*\\*\\*";
    public static final String BOLD_BRACKETS_REGEX = "【.*】";
    public static final String COLON_REGEX = "：";

    public static String clean(String input) {
        String s = cleanLineNumberPrefix(input);
        s = cleanBoldPrefix(s);
        s = cleanBoldBracketsPrefix(s);
        // 中文冒号放后面处理
        s = cleanColonPrefix(s);
        StringBuilder sb = new StringBuilder(s.trim());
        // 最后处理引号、星号、横杠等内容
        cleanQuotations(sb);
        return sb.toString();
    }

    private static String cleanColonPrefix(String input) {
        return input.startsWith(COLON_REGEX) ? input.replaceFirst(COLON_REGEX, "") : input;
    }

    private static String cleanBoldBracketsPrefix(String input) {
        return input.replaceFirst(BOLD_BRACKETS_REGEX, "");
    }

    private static String cleanBoldPrefix(String input) {
        return input.replaceFirst(BOLD_REGEX, "");
    }

    private static String cleanLineNumberPrefix(String input) {
        return input.replaceFirst(Constants.SEQUENCE_REGEX, "").trim();
    }

    private static void cleanQuotations(StringBuilder sb) {

        if (sb.length() > 1) {
            if ((sb.charAt(0) == '：')) {
                sb.deleteCharAt(0);
            }
        }

        if (sb.length() > 2) {
            if ((sb.charAt(0) == '-' || sb.charAt(0) == '*') && sb.charAt(1) == ' ') {
                sb.delete(0, 2);
            }
        }

        // 去掉最外层的引号
        if (sb.length() > 2) {
            if (sb.charAt(0) == '“' || sb.charAt(0) == '\"') {
                if (sb.charAt(sb.length() - 1) == '”' || sb.charAt(sb.length() - 1) == '\"') {
                    sb.deleteCharAt(0);
                    sb.deleteCharAt(sb.length() - 1);
                }
            }
        }
    }
}
